package org.idea.spring.resource;

import org.springframework.core.io.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author linhao
 * @date created in 1:53 下午 2020/10/28
 */
public class ResourceDemo {


    public static void main(String[] args) throws IOException {
        String resourcePath = "classpath:*.*";
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources(resourcePath);
        for (Resource resource : resources) {
            System.out.println(resource.getDescription());
        }
        String filePath = "test.txt";
        String posPath = "/Users/linhao/IdeaProjects/2020-project/spring-git/spring-frameworker/spring-framework/spring-core/spring-resource/src/main/resources/test.txt";
        Resource resource = new ClassPathResource(filePath);
        // 1. 使用系统的文件路径方式加载文件
        WritableResource resource1 = new PathResource(posPath);

        // 2. 使用类路径方式加载文件
        Resource resource2 = new ClassPathResource(filePath);
        System.out.println("============");

        //通过使用spring内置的resource api 可以灵活处理资源的信息写入和读取功能
        System.out.println(resource1.getFilename());
        System.out.println(resource2.getFilename());

        //将数据写入到文件里面
        OutputStream outputStream = resource1.getOutputStream();
        outputStream.write("test is test".getBytes());

        InputStream inputStream = resource2.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        byte[] bytes = new byte[50];
        bufferedInputStream.read(bytes);
        System.out.println("文本内容是：" + new String(bytes));

    }
}
